<template>
  <view
    class="video-container"
    :class="{ 'show-comments': showComments }"
    :style="{ backgroundImage: 'url(' + test + ')' }"
  >
    <swiper
      class="video-swiper"
      :current="current"
      @change="onChange"
      vertical
      :circular="true"
    >
      <swiper-item v-for="(item, index) in videoList" :key="index">
        <view class="video-wrapper" :class="{ 'mini-video': showComments }">
          <!-- 					<video :id="'video_' + index" class="video" :src="item.videoUrl" :poster="item.poster"   @loadedmetadata="getVideoSize"
						:show-center-play-btn="false" :controls="true" :loop="true" :enable-progress-gesture="false"
					   object-fit='contain'  @click="togglePlay(index)" @ended="onEnded(index)">
					</video> -->

          <!-- 追加视频背景图方案 -->
          <image class="videobg" :src="item.poster" mode="aspectFill"></image>
          <view
            class="video-container2"
            :style="{ height: videoHeight + 'px' }"
          >
            <video
              v-if="current === index"
              :id="'video_' + index"
              class="video2"
              :src="item.videoUrl"
              @loadedmetadata="getVideoSize"
              :show-center-play-btn="false"
              :controls="true"
              :loop="true"
              :enable-progress-gesture="false"
              object-fit="fill"
              @click="togglePlay(index)"
              @ended="onEnded(index)"
            ></video>
          </view>

          <!-- 视频信息层 -->
          <view class="video-info" :class="{ hide: showComments }">
            <!-- 作者信息 -->
            <view class="author-info">
              <text class="author-name">@{{ item.author }}</text>
              <text class="video-desc">{{ item.description }}</text>
            </view>

            <!-- 右侧操作按钮 -->
            <view class="action-buttons" v-if="showBtn">
              <view class="action-item" @tap="toAuthor(item.author_id)">
                <image
                  class="avatar"
                  :src="item.authorAvatar"
                  mode="aspectFill"
                ></image>
              </view>
              <view class="action-item" @tap="toggleCollect">
                <image
                  class="icon"
                  v-if="!item.collectstatus"
                  src="../static/img/collect.png"
                ></image>
                <image
                  class="icon"
                  v-if="item.collectstatus"
                  src="../static/img/collected.png"
                ></image>
                <text class="count">{{ item.collects }}</text>
              </view>
              <view class="action-item" @tap="toggleLike">
                <image
                  class="icon"
                  v-if="!item.likestatus"
                  src="../static/img/zan.png"
                ></image>
                <image
                  class="icon"
                  v-if="item.likestatus"
                  src="../static/img/zan2.png"
                ></image>
                <text class="count">{{ item.likes }}</text>
              </view>
              <view class="action-item" @tap="handleComment(index)">
                <image class="icon" src="../static/img/pl.png"></image>
                <text class="count">{{ item.comments }}</text>
              </view>
              <button class="action-item" @tap="shareVideo" open-type="share">
                <image class="icon" src="../static/img/fx.png"></image>
                <text class="count">分享</text>
              </button>
            </view>

            <view class="action-buttons" v-if="showPro">
              <view class="pro-info" @click="toPro(item.proid)">
                <image :src="item.pic" class="pro-icon"></image>
                <text class="pro-text">查看商品</text>
              </view>
            </view>
          </view>
        </view>
      </swiper-item>
    </swiper>

    <!-- 引入评论组件 -->
    <!-- <pl :show="showComments" @close="closeComments"></pl> -->
    <comment
      :show="showComments"
      @close="closeComments"
      :listid="listid"
      :id="id"
    ></comment>
  </view>
</template>

<script>
import pl from "./pl.vue";
import comment from "./comment.vue";
var app = getApp();
export default {
  components: {
    pl,
    comment,
  },
  data() {
    return {
      videoHeight: 200, // 默认高度
      static_url: app.globalData.static_url,
      current: 0,
      videoList: [
        // {
        //     id: 1,
        //     videoUrl: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250125/dd81a8f0e2a663e896801457e0ade38b.mp4',
        //     poster: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
        //     author: '用户昵称1',
        //     authorAvatar: '../static/img/album.png',
        //     description: '视频描述文字 #话题标签',
        //     likes: '12.5w',
        //     collects: '1',
        //     comments: '2.8w',
        //     likestatus: 0,
        //     collectstatus: 1
        // },
        // {
        //     id: 2,
        //     videoUrl: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250106/5ae005872a7e9d6fefe422d8291feebd.mp4',
        //     poster: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
        //     author: '用户昵称2',
        //     authorAvatar: '../static/img/album.png',
        //     description: '第二个视频描述 #另一个话题',
        //     likes: '8.9w',
        //     collects: '1',
        //     comments: '1.2w',
        //     likestatus: 1,
        //     collectstatus: 0
        // },
        // {
        //     id: 3,
        //     videoUrl: 'https://hedashepin.oss-cn-guangzhou.aliyuncs.com/upload/3/20250329/a59331c7459e43f97e090cf3f03e6cae.mp4',
        //     poster: 'https://heda123.oss-cn-guangzhou.aliyuncs.com/upload/3/20250121/e41d7fe8ead48f06290c699d6d6d36e9.jpg',
        //     author: '用户昵称2',
        //     authorAvatar: '../static/img/album.png',
        //     description: '第二个视频描述 #另一个话题',
        //     likes: '8.9w',
        //     collects: '1',
        //     comments: '1.2w',
        //     likestatus: 1,
        //     collectstatus: 1
        // }
      ],
      nextVideoList: [], //下一个播放合集
      isPlaying: true,
      showComments: false,
      listid: 0, //视频id
      id: 0, //合集id
      limit: 5,
      page: 1,
      canload: true,
      currentVideo: null,
      videolive: null,
      showBtn: false,
      showPro: false,
      test: "",
    };
  },

  onLoad: function (opt) {
    // opt.id = 1;
    // this.id = opt.id;
    // if (opt.id) {
    //     this.id = opt.id;
    // } else {
    //     app.error("参数缺少，请重试")
    // }
    // if (opt.listid) {
    //     this.listid = opt.listid;
    // }
    this.videolive = app.globalData.videolive;
    if (this.videolive.type == 1) {
      this.showBtn = false;
      this.showPro = true;
      this.getdata1();
    } else {
      this.showBtn = true;
      this.showPro = false;
      this.getdata3();
      // if (this.videolive.list.length > 0) {
      //     if (this.videolive.list.length == 1) {
      //         this.id = this.videolive.list[0].video_list_id;
      //         this.getdata2()
      //     } else {
      //         this.id = this.videolive.list[0].video_list_id;
      //         this.getdata2();
      //         setTimeout(() => {
      //             this.getdata22();
      //         }, 1000)
      //     }

      // } else {
      //     this.getdata3()
      // }
    }
  },
  mounted() {
    // 自动播放第一个视频
    setTimeout(() => {
      const video = uni.createVideoContext("video_0", this);
      video.play();
    }, 500);
  },
  methods: {
    getdata1() {
      let that = this;
      app.showLoading("加载中");
      that.videoList = that.videolive.list.map((c) => {
        return {
          id: c.id,
          videoUrl: c.imgurl,
          // poster: c.image,
          author: app.globalData.initdata.name,
          authorAvatar: app.globalData.initdata.logo,
          description: app.globalData.initdata.desc,
          // likes: c.thumbs,
          // collects: c.collects,
          // comments: c.evaluations,
          // likestatus: c.is_thumb,
          // collectstatus: c.is_collect
          //---------
          name: c.name,
          pic: c.pic,
          proid: c.proid,
        };
      });
      app.showLoading(false);
    },

    getdata2() {
      app.showLoading("加载中");
      var that = this;
      app.get("VideoCenter/info?id=" + that.id, {}, function (res) {
        if (res && res.status == 200) {
          // that.cname = res.data.name;
          // that.videoUrl = res.data.video;
          // that.cimage = res.data.image;
          // that.introduction = res.data.introduction;
          // that.createtime = res.data.createtime;
          // that.author_nickname = res.data.author_nickname;
          // that.author_headimg = res.data.author_headimg;
          // that.isFollow = res.data.is_involved;
          // that.pageviews = res.data.pageviews;
          if (!res.data.video_list || res.data.video_list.length == 0) {
            app.error("当前合集没有视频~");
          } else {
            // that.videoList = res.data.video_list;
            that.videoList = res.data.video_list.map((c) => {
              return {
                cid: res.data.id,
                id: c.id,
                videoUrl: c.video,
                poster: c.image,
                author_id: res.data.author_id,
                author: res.data.author_nickname,
                authorAvatar: res.data.author_headimg,
                description: c.name,
                likes: c.thumbs,
                collects: c.collects,
                comments: c.evaluations,
                likestatus: c.is_thumb,
                collectstatus: c.is_collect,
              };
            });
            that.listid = that.videoList[0].id;
            that.currentVideo = that.videoList[0];
          }

          // if (that.listid) {
          //     that.currentVideo = that.videoList.find(item => item.id == that.listid);
          //     that.currentEpisode = that.videoList.findIndex(item => item.id == that.listid);
          //     that.currentVideoSrc = that.currentVideo.video;
          //     that.isCollected = that.currentVideo.is_collect;
          //     that.isLiked = that.currentVideo.is_thumb;
          //     that.commentNumber = that.currentVideo.evaluations;
          // } else {
          //     that.currentVideo = that.videoList[0];
          //     that.listid = that.currentVideo.id;
          //     that.currentVideoSrc = that.currentVideo.video;
          //     that.isCollected = that.currentVideo.is_collect;
          //     that.isLiked = that.currentVideo.is_thumb;
          //     that.commentNumber = that.currentVideo.evaluations;
          // }
          that.viewAdd(that.listid);
          app.showLoading(false);
        } else {
          app.showLoading(false);
          app.error(res.msg);
        }
        that.loaded();
      });
    },

    getdata3() {
      app.showLoading("加载中");
      var that = this;
      var ids = that.videolive.list.map((item) => item.video_list_id).join(",");
      app.get(
        "VideoCenter/videoList",
        { id: ids, page: that.page, limit: that.limit },
        function (res) {
          if (res && res.status == 200) {
            if (!res.data || res.data.length == 0) {
            } else {
              that.videoList = res.data.map((c) => {
                return {
                  cid: res.data.id,
                  id: c.id,
                  videoUrl: c.video,
                  poster: c.image,
                  author_id: c.author_involved,
                  author: c.author_nickname,
                  authorAvatar: c.author_headimg,
                  description: c.name,
                  likes: c.thumbs,
                  collects: c.collects,
                  comments: c.evaluations,
                  likestatus: c.is_thumb,
                  collectstatus: c.is_collect,
                };
              });
              that.listid = that.videoList[0].id;
              that.currentVideo = that.videoList[0];
            }
            that.viewAdd(that.listid);
            app.showLoading(false);
          } else {
            app.showLoading(false);
            app.error(res.msg);
          }
          that.loaded();
        }
      );
    },

    getNextPage() {
      // console.log("加载下一页", this.page)
      var that = this;
      var ids = that.videolive.list.map((item) => item.video_list_id).join(",");
      that.nextVideoList = [];
      app.get(
        "VideoCenter/videoList",
        { id: ids, page: that.page, limit: that.limit },
        function (res) {
          if (res && res.status == 200) {
            if (!res.data || res.data.length == 0) {
              that.canload = false;
            } else {
              that.nextVideoList = res.data.map((c) => {
                return {
                  cid: res.data.id,
                  id: c.id,
                  videoUrl: c.video,
                  poster: c.image,
                  author_id: c.author_involved,
                  author: c.author_nickname,
                  authorAvatar: c.author_headimg,
                  description: c.name,
                  likes: c.thumbs,
                  collects: c.collects,
                  comments: c.evaluations,
                  likestatus: c.is_thumb,
                  collectstatus: c.is_collect,
                };
              });
              that.videoList.push(...that.nextVideoList);
            }
          }
        }
      );
    },

    //#region 方案2

    getdata22() {
      let that = this;
      for (let index = 0; index < that.videolive.list.length; index++) {
        const element = that.videolive.list[index];
        if (index == 0) {
          continue;
        }
        that.getNextVideoList(element.video_list_id);
        console.log("合集数据累计，", index, that.videoList);
      }
    },

    getNextVideoList(id) {
      var that = this;
      that.nextVideoList = [];
      console.log("nextVideoList", id);
      app.get("VideoCenter/info?id=" + id, {}, function (res) {
        if (res && res.status == 200) {
          if (!res.data.video_list || res.data.video_list.length == 0) {
          } else {
            that.nextVideoList = res.data.video_list.map((c) => {
              return {
                cid: res.data.id,
                id: c.id,
                videoUrl: c.video,
                poster: c.image,
                author_id: res.data.author_id,
                author: res.data.author_nickname,
                authorAvatar: res.data.author_headimg,
                description: c.name,
                likes: c.thumbs,
                collects: c.collects,
                comments: c.evaluations,
                likestatus: c.is_thumb,
                collectstatus: c.is_collect,
              };
            });
            that.videoList.push(...that.nextVideoList);
          }
        }
      });
    },

    //#endregion

    getVideoSize(event) {
      if (event && event.detail) {
        // 获取视频原始尺寸
        const { width, height } = event.detail;

        // 获取容器实际宽度
        const query = uni.createSelectorQuery().in(this);
        query
          .select(".video-container2")
          .boundingClientRect((data) => {
            const containerWidth = data.width;
            // 计算保持比例的高度
            this.videoHeight = containerWidth * (height / width);
          })
          .exec();
      }
    },

    // 增加浏览量
    viewAdd(vid) {
      app.post(
        "VideoCenter/pageviewsAdd",
        { video_center_content_id: vid },
        function (res) {
          if (res && res.status == 200) {
          } else {
            console.log(res.msg);
          }
        }
      );
    },

    toPro(id) {
      app.goto("/pages/shop/product?id=" + id);
    },

    onChange(e) {
      let that = this;
      const index = e.detail.current;
      this.current = index;
      console.log("切换视频:", index);
      this.getVideoSize();
      this.listid = this.videoList[index].id;
      this.id = this.videoList[index].cid;
      this.currentVideo = this.videoList[index];
      this.viewAdd(this.listid);

      if (
        this.videolive.type == 2 &&
        this.canload &&
        index + 1 == this.videoList.length
      ) {
        this.page += 1;
        this.getNextPage();
      }
      // 停止其他视频播放
      // this.videoList.forEach((item, i) => {
      //     if (i !== index) {
      //         const video = uni.createVideoContext('video_' + i, this);
      //         video.pause();
      //     }
      // });
      // // 播放当前视频
      // const video = uni.createVideoContext('video_' + index, this);
      // video.play();

      // 追加视频背景图方案
      setTimeout(() => {
        const video = uni.createVideoContext("video_" + index, that);
        video.play();
      }, 500);
    },

    togglePlay(index) {
      const video = uni.createVideoContext("video_" + index, this);
      if (this.isPlaying) {
        video.pause();
      } else {
        video.play();
      }
      this.isPlaying = !this.isPlaying;
    },

    onEnded(index) {
      const video = uni.createVideoContext("video_" + index, this);
      video.play(); // 循环播放
    },

    handleComment(index) {
      this.showComments = true;
      // 添加视频缩小动画
      setTimeout(() => {
        const video = uni.createVideoContext("video_" + index, this);
        video.play(); // 确保视频继续播放
      }, 300);
    },

    closeComments() {
      this.showComments = false;
    },

    toggleLike() {
      let that = this;
      that.videoList[that.current].likestatus =
        !that.videoList[that.current].likestatus;
      let type = !that.videoList[that.current].likestatus ? 2 : 1;
      if (type == 1) {
        that.videoList[that.current].likes += 1;
      } else {
        that.videoList[that.current].likes -= 1;
      }
      app.post(
        "VideoCenter/thumbSet",
        { video_center_content_id: that.listid, type: type },
        function (res) {
          if (res && res.status == 200) {
            if (that.isLiked) {
              //app.success('点赞成功');
            }
          } else {
            if (res.msg == "已点赞") {
            } else {
              app.error(res.msg);
              that.videoList[that.current].likestatus =
                !that.videoList[that.current].likestatus;
            }
          }
        }
      );
    },

    toggleCollect() {
      let that = this;
      that.videoList[that.current].collectstatus =
        !that.videoList[that.current].collectstatus;
      let type = !that.videoList[that.current].collectstatus ? 2 : 1;
      if (type == 1) {
        that.videoList[that.current].collects += 1;
      } else {
        that.videoList[that.current].collects -= 1;
      }
      app.post(
        "VideoCenter/collectsSet",
        { video_center_content_id: that.listid, type: type },
        function (res) {
          if (res && res.status == 200) {
            if (that.isCollected) {
              // app.success('收藏成功');
            }
          } else {
            if (res.msg == "已收藏此视频") {
            } else {
              app.error(res.msg);
              that.videoList[that.current].collectstatus =
                !that.videoList[that.current].collectstatus;
            }
          }
        }
      );
    },

    toAuthor(author_id) {
      uni.navigateTo({
        url: `/pagesZone/video/author_detail?id=${author_id}`,
      });
    },

    shareVideo() {
      let that = this;
      that.share_title = that.currentVideo.description;
      that.share_path =
        "/pagesZone/video/video_detail?id=" +
        that.id +
        "&listid=" +
        that.listid;
      that.share_imageUrl = that.currentVideo.poster;
      uni.share({
        title: that.share_title,
        path: that.share_path,
        imageUrl: that.share_imageUrl,
      });
    },
  },
  onShareAppMessage() {
    return {
      title: this.share_title,
      path: this.share_path,
      imageUrl: this.share_imageUrl,
    };
  },
};
</script>

<style lang="scss">
.video-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  // background-color: #000;

  &.show-comments {
    background-color: #f5f5f5;
  }

  .video-wrapper {
    width: 100%;
    height: 100%;
    transition: all 0.3s ease-out;
    display: flex; //追加视频背景图方案
    background-color: #000;

    .videobg {
      position: absolute;
      width: 100vw;
      height: 100vh;
    }

    &.mini-video {
      height: 25vh;
      position: relative;
      z-index: 1000;
    }
  }

  .video-swiper {
    width: 100%;
    height: 100%;
  }

  .video {
    width: 100%;
    height: 100%;
    transition: all 0.3s ease-out;
    // ::v-deep .uni-video-container {
    // 	background-color: transparent;
    // }
  }

  //追加视频背景图方案
  .video-container2 {
    width: 100%;
    background-color: #000;
    margin: auto;

    .video2 {
      width: 100%;
      height: 100%;
      transition: all 0.3s ease-out;
    }
  }

  .video-info {
    position: absolute;
    // bottom: 120rpx;
    bottom: 40rpx; //追加视频背景图方案
    left: 0;
    right: 0;
    padding: 0 20rpx;
    z-index: 1;
    transition: opacity 0.3s ease-out;

    &.hide {
      opacity: 0;
    }

    .author-info {
      padding-right: 120rpx;

      .author-name {
        color: #fff;
        font-size: 30rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
        display: block;
      }

      .video-desc {
        color: #fff;
        font-size: 28rpx;
        line-height: 1.4;
        display: block;
      }
    }

    .action-buttons {
      position: absolute;
      right: 20rpx;
      bottom: 0;
      display: flex;
      flex-direction: column;
      align-items: center;

      .action-item {
        margin-bottom: 50rpx;
        display: flex;
        flex-direction: column;
        align-items: center;

        .avatar {
          width: 100rpx;
          height: 100rpx;
          border-radius: 50%;
          border: 4rpx solid #fff;
          margin-bottom: 10rpx;
        }

        .icon {
          width: 70rpx;
          height: 70rpx;
          margin-bottom: 6rpx;
        }

        .count {
          color: #fff;
          font-size: 26rpx;
        }
      }

      .pro-info {
        display: flex;
        flex-direction: column;
        border-radius: 20rpx;
        overflow: hidden;

        .pro-icon {
          width: 120rpx;
          height: 120rpx;
        }

        .pro-text {
          position: absolute;
          font-size: 24rpx;
          margin: 0 auto;
          color: #fff;
          text-align: center;
          background: linear-gradient(
            to top,
            /* 渐变方向（默认从上到下，可不写） */ rgba(128, 128, 128, 1),
            /* 起始颜色（灰色，不透明） */ rgba(128, 128, 128, 0)
              /* 结束颜色（灰色，完全透明） */
          );
          opacity: 0.8;
          bottom: 0;
          width: 100%;
          border-radius: 0 0rpx 20rpx 20rpx;
        }
      }
    }
  }
}
</style>
